package doantotnghiep.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import convertobject.Convert;
import doantotnghiep.business.MedicamentBusiness;
import doantotnghiep.business.PurchaseOrderBusiness;
import doantotnghiep.dao.StaffDao;
import doantotnghiep.model.Customer;
import doantotnghiep.model.Medicament;
import doantotnghiep.model.PurchaseOrder;
import doantotnghiep.model.PurchaseOrderDetail;
import doantotnghiep.model.Staff;
import doantotnghiep.modelDTO.CustomerDTO;
import doantotnghiep.modelDTO.MedicamentDTO;
import doantotnghiep.modelDTO.PurchaseOrderDTO;
import doantotnghiep.modelDTO.PurchaseOrderDetailDTO;
import doantotnghiep.modelDTO.StaffDTO;

@Controller
public class PurchaseOrderController {

	@Autowired
	private PurchaseOrderBusiness purchaseOrderBusiness;

	@Autowired
	private MedicamentBusiness medicamentBusiness;

	private Customer customer;

	private CustomerDTO customerDto;

	private Staff staff;

	private StaffDTO staffDto;

	private MedicamentDTO medicamentDTO;

	@Autowired
	private PurchaseOrder purchaseOrder;

	@Autowired
	private StaffDao staffDao;
	private static ArrayList<PurchaseOrderDetailDTO> purchaseOrderDetailDTOs;
	private static int countOfDetail = 0;

	@ModelAttribute("PurchaseOrderDTO")
	public PurchaseOrderDTO getPurchaseObject() {
		return new PurchaseOrderDTO();
	}

	@ModelAttribute("PurchaseOrderDetailDTO")
	public PurchaseOrderDetailDTO getPurchaseDetailObject() {
		return new PurchaseOrderDetailDTO();
	}

	@RequestMapping(value = "/viewPurchases", method = RequestMethod.GET)
	public ModelAndView viewAllPurchase() {
		List<PurchaseOrder> purchases = purchaseOrderBusiness.getAllPurchase();
		List<PurchaseOrderDTO> purchaseDTOs = new ArrayList<PurchaseOrderDTO>();
		purchaseDTOs = Convert.convertToPurchaseOrderDTO(purchases);
		Map<String, Object> purchaseModel = new HashMap<String, Object>();
		purchaseModel.put("purchaseDTOs", purchaseDTOs);
		return new ModelAndView("viewPurchases", "purchaseModel", purchaseModel);
	}

	@RequestMapping(value = "/searchPurchases", method = RequestMethod.GET)
	public ModelAndView searchPurchases(HttpServletRequest request,
			ModelMap model, String orderDate) {
		List<PurchaseOrder> purchases = purchaseOrderBusiness
				.getAllPurchaseByOrderDate(orderDate);
		List<PurchaseOrderDTO> purchaseDTOs = new ArrayList<PurchaseOrderDTO>();
		purchaseDTOs = Convert.convertToPurchaseOrderDTO(purchases);
		Map<String, Object> purchaseModel = new HashMap<String, Object>();
		purchaseModel.put("purchaseDTOs", purchaseDTOs);
		return new ModelAndView("purchasesSearchResult", "purchaseModel",
				purchaseModel);
	}

	@RequestMapping(value = "/addPurchaseOrder", method = RequestMethod.GET)
	public ModelAndView addPurchaseOrder() {
		purchaseOrderDetailDTOs = new ArrayList<PurchaseOrderDetailDTO>();
		List<Customer> customers;
		List<CustomerDTO> customerDTOs = new ArrayList<CustomerDTO>();
		List<Staff> staffs;
		List<StaffDTO> staffDTOs = new ArrayList<StaffDTO>();

		// get all customer
		customers = purchaseOrderBusiness.getAllCustomer();
		for (Customer c : customers) {
			customerDto = new CustomerDTO();
			customerDto.setId(c.getId());
			customerDto.setFullName(c.getFullName());
			customerDTOs.add(customerDto);
		}

		// get all staff
		staffs = staffDao.listPurchaseValidStaff();
		for (Staff st : staffs) {
			staffDto = new StaffDTO();
			staffDto.setId(st.getId());
			staffDto.setFullName(st.getFullName());

			staffDTOs.add(staffDto);
		}

		// add list staff and customer into map
		Map<String, Object> purchaseModel = new HashMap<String, Object>();
		purchaseModel.put("customerDTOs", customerDTOs);
		purchaseModel.put("staffDTOs", staffDTOs);

		return new ModelAndView("addPurchaseOrder", "purchaseModel",
				purchaseModel);
	}

	@RequestMapping(method = RequestMethod.POST, value = "/addPurchaseOrder")
	public synchronized String addPurchaseOrder(
			HttpServletRequest request,
			ModelMap model,
			@ModelAttribute("PurchaseOrderDTO") PurchaseOrderDTO purchaseOrderDTO) {
		if (purchaseOrderDTO != null && countOfDetail > 0) {
			purchaseOrder.setDeliveryDate(purchaseOrderDTO.getDeliveryDate());
			purchaseOrder.setDeliveryLocation(purchaseOrderDTO
					.getDeliveryLocation());
			purchaseOrder.setOrderedDate(purchaseOrderDTO.getOrderedDate());

			customer = new Customer();
			customer.setId(purchaseOrderDTO.getCustomer_ID());
			purchaseOrder.setCustomer(customer);

			staff = new Staff();
			staff.setId(purchaseOrderDTO.getStaff_ID());
			purchaseOrder.setStaff(staff);

			purchaseOrderBusiness.addPurchase(purchaseOrder);
			System.out.println("purchase inserted! ");
		}
		return "redirect:/finishAddOrder";
	}

	@RequestMapping(value = "/findMedicamentByName", method = RequestMethod.GET)
	public ModelAndView findMedicamentByName(HttpServletRequest request,
			ModelMap model, String key) {
		ArrayList<MedicamentDTO> medicamentDTOs = new ArrayList<MedicamentDTO>();
	
		List<Medicament> medicaments = medicamentBusiness
				.getAllMedicamentByKeyWord(key);

		if (medicaments != null) {

			for (Medicament m : medicaments) {
				MedicamentDTO meDto = new MedicamentDTO();
				meDto.setId(m.getId());
				meDto.setMedicamentName(m.getMedicamentName());
				meDto.setTotalOfBatch(m.getTotalOfBatch());

				medicamentDTOs.add(meDto);
			}
			Map<String, Object> orderDetailModel = new HashMap<String, Object>();
			orderDetailModel.put("medicamentDTOs", medicamentDTOs);// list all
																	// medicine
																	// by name
			orderDetailModel.put("purchaseOrderDetailDTOs",
					purchaseOrderDetailDTOs);// list detail entered
			return new ModelAndView("addOrderDetail", "orderDetailModel",
					orderDetailModel);
		}

		return new ModelAndView();
	}

	@RequestMapping(value = "/addOrderDetail", method = RequestMethod.GET)
	public ModelAndView addDetail() {

		/*
		 * List<Medicament> medicaments; List<MedicamentDTO> medicamentDTOs =
		 * new ArrayList<MedicamentDTO>();
		 * 
		 * //get all medicament medicaments =
		 * medicamentBusiness.listMedicament(); for (Medicament m : medicaments)
		 * { medicamentDTO = new MedicamentDTO();
		 * 
		 * medicamentDTO.setId(m.getId());
		 * medicamentDTO.setMedicamentName(m.getMedicamentName());
		 * medicamentDTO.setTotalOfBatch(m.getTotalOfBatch());
		 * medicamentDTOs.add(medicamentDTO); }
		 */

		// put data into map
		Map<String, Object> orderModel = new HashMap<String, Object>();
		orderModel.put("purchaseOrderDetailDTOs", purchaseOrderDetailDTOs);

		return new ModelAndView("addOrderDetail");
	}

	@RequestMapping(value = "/addOrderDetail", method = RequestMethod.POST)
	public synchronized ModelAndView addDetail(
			HttpServletRequest request,
			ModelMap model,
			@ModelAttribute("PurchaseOrderDetailDTO") PurchaseOrderDetailDTO purchaseOrderdetailDTO) {
		List<MedicamentDTO> medicamentDTOs = new ArrayList<MedicamentDTO>();
		Map<String, Object> orderDetailModel = new HashMap<String, Object>();
		
		// put data into map
		orderDetailModel.put("medicamentDTOs", medicamentDTOs);

		if (purchaseOrderdetailDTO != null) {
			String medicamentName = medicamentBusiness.getMedicamentById(
					purchaseOrderdetailDTO.getMedicament_ID())
					.getMedicamentName();
			purchaseOrderdetailDTO.setMedicamentName(medicamentName);
			Medicament medicine = medicamentBusiness
					.getMedicamentById(purchaseOrderdetailDTO
							.getMedicament_ID());
			int numberBatch = purchaseOrderdetailDTO.getTotalBatch();
			float sellPrice = medicine.getSellPrice();
			float orderCost = numberBatch * sellPrice;
			purchaseOrderdetailDTO.setOrderCost(orderCost);

			purchaseOrderDetailDTOs.add(countOfDetail, purchaseOrderdetailDTO);
			countOfDetail++;
		}
		orderDetailModel
				.put("purchaseOrderDetailDTOs", purchaseOrderDetailDTOs);
		return new ModelAndView("addOrderDetail", "orderDetailModel",
				orderDetailModel);
	}

	@RequestMapping(value = "/deletePurchase", method = RequestMethod.GET)
	public String deletePurchase(HttpServletRequest request, ModelMap model,
			int id) {
		List<PurchaseOrderDetail> details = purchaseOrderBusiness
				.getAllOrderDetailByID(id);
		if (details != null) {
			for (int i = 0; i < details.size(); i++) {
				purchaseOrderBusiness.deleteOrderDetail(details.get(i).getId());
			}
		}
		purchaseOrderBusiness.deletePurchase(id);
		return "redirect:/viewPurchases";
	}

	@RequestMapping(value = "/finishAddOrder", method = RequestMethod.GET)
	public synchronized String addOrderAndDetail() {
		if (purchaseOrderDetailDTOs != null && countOfDetail > 0) {
			System.out.println("start! add order detail");
			int currentOrderID = purchaseOrderBusiness.getCurrentPurchase();
			System.out.println("current id purchase: " + currentOrderID);
			// System.out.println("size cua list orderdetail: "+(getCountOfDetail()));
			for (int i = 0; i < countOfDetail; i++) {
				PurchaseOrderDetailDTO detailDTO = purchaseOrderDetailDTOs
						.get(i);
				if (detailDTO != null && detailDTO.getTotalBatch() > 0) {
					PurchaseOrderDetail purchaseOrderDetail = new PurchaseOrderDetail();

					PurchaseOrder purchaseOrder = new PurchaseOrder();
					purchaseOrder.setOrderID(currentOrderID);
					purchaseOrderDetail.setPurchaseOrder(purchaseOrder);

					purchaseOrderDetail
							.setTotalBatch(detailDTO.getTotalBatch());

					Medicament medicament = new Medicament();
					medicament.setId(detailDTO.getMedicament_ID());
					purchaseOrderDetail.setMedicament(medicament);

					// decrease number batch of this medicine
					medicamentBusiness.decreaseNumberofBatch(
							detailDTO.getMedicament_ID(),
							detailDTO.getTotalBatch());

					purchaseOrderDetail.setOrderCost(detailDTO.getOrderCost());

					purchaseOrderBusiness.addOrderDetail(purchaseOrderDetail);
				}
			}
			purchaseOrderDetailDTOs.clear();
			countOfDetail = 0;
		}
		return "redirect:/viewPurchases";

	}

	@RequestMapping(value = "/detailPurchase", method = RequestMethod.GET)
	public ModelAndView getOrderDetailByID(HttpServletRequest request,
			ModelMap model, int id) {
		ArrayList<PurchaseOrderDetailDTO> orderDetailDTOs = new ArrayList<PurchaseOrderDetailDTO>();
		ArrayList<PurchaseOrderDetail> orderDetails = purchaseOrderBusiness
				.getOrderDetailByID(id);
		if (orderDetails != null) {
			System.out.println("co " + orderDetails.size()
					+ "chi tiet trong phieu dat hang nay");
			for (int i = 0; i < orderDetails.size(); i++) {
				PurchaseOrderDetail pDetail = orderDetails.get(i);
				PurchaseOrderDetailDTO purchaseOrderDetailDTO = new PurchaseOrderDetailDTO();
				purchaseOrderDetailDTO.setId(pDetail.getId());
				purchaseOrderDetailDTO.setMedicament_ID(pDetail.getMedicament()
						.getId());
				purchaseOrderDetailDTO.setMedicamentName(pDetail
						.getMedicament().getMedicamentName());
				purchaseOrderDetailDTO.setTotalBatch(pDetail.getTotalBatch());
				purchaseOrderDetailDTO.setOrderCost(pDetail.getOrderCost());
				orderDetailDTOs.add(purchaseOrderDetailDTO);
			}
			Map<String, Object> orderDetailModel = new HashMap<String, Object>();
			orderDetailModel.put("orderDetailDTOs", orderDetailDTOs);
			return new ModelAndView("viewOrderDetail", "orderDetailModel",
					orderDetailModel);
		}

		return new ModelAndView();
	}
}
